<template>
    <div class="divBox">
        <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
            <el-form-item>
                <el-input v-model="dataForm.batchName" placeholder="批次名称" clearable></el-input>
            </el-form-item>
            <el-form-item>
                <el-input v-model="dataForm.integralCode" placeholder="积分码" clearable></el-input>
            </el-form-item>
            <el-form-item>
                <el-input v-model="dataForm.phone" placeholder="用户手机" clearable></el-input>
            </el-form-item>
            <el-form-item>
                <el-select v-model="dataForm.used" clearable placeholder="请选择是否使用" >
                    <el-option label="未使用" :value="0"> </el-option>
                    <el-option label="已使用" :value="1"> </el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-select v-model="dataForm.userLimit" clearable placeholder="请选择领取范围">
                    <el-option label="所有" :value="0"> </el-option>
                    <el-option label="经销商" :value="1"> </el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button @click="getDataList()">查询</el-button>
                <el-button v-hasPermi="['admin:integralcode:save']" type="primary"
                    @click="addOrUpdateHandle()">新增</el-button>
                <el-button @click="exportExcel()">导出</el-button>
                <el-button v-hasPermi="['admin:integralcode:delete']" type="danger" @click="deleteHandle()"
                    :disabled="dataListSelections.length <= 0">批量删除
                </el-button>
                <el-button type="danger" @click="batchUpdate()"  >批量修改
                </el-button>
            </el-form-item>
        </el-form>
        <el-table :data="dataList" border v-loading="dataListLoading" @selection-change="selectionChangeHandle"
            style="width: 100%;">
            <el-table-column type="selection" header-align="center" align="center" width="50">
            </el-table-column>
            <!-- <el-table-column prop="id" header-align="center" align="center" label="">
            </el-table-column> -->
            <el-table-column prop="integralCode" header-align="center" align="center" label="积分码">
            </el-table-column>
            <el-table-column prop="batchName" header-align="center" align="center" label="批次名称">
            </el-table-column>
            <el-table-column prop="userLimit" header-align="center" align="center" label="领取范围">
                <template slot-scope="scope">
                    <span v-if="scope.row.userLimit == 1">经销商</span>
                    <span v-if="scope.row.userLimit == 0">所有</span>
                </template>
            </el-table-column>
            <el-table-column prop="codeType" header-align="center" align="center" label="类型">
                <template slot-scope="scope">
                    <span v-if="scope.row.codeType == 1">随机</span>
                    <span v-if="scope.row.codeType == 0">固定</span>
                </template>
            </el-table-column>
            <el-table-column prop="addNumber" header-align="center" align="center" label="积分数量">
                <template slot-scope="scope">
                    <span v-if="scope.row.codeType == 0">{{scope.row.addNumber}}</span>
                    <span v-if="scope.row.codeType == 1"> {{scope.row.maxNumber}}到{{ scope.row.minNumber }},间隔:{{ scope.row.intervalNumber }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="used" header-align="center" align="center" label="是否使用">
                <template slot-scope="scope">
                    <span v-if="scope.row.used == 1">已使用</span>
                    <span v-if="scope.row.used == 0">未使用</span>
                </template>
            </el-table-column>
            <el-table-column prop="useTime" header-align="center" align="center" label="使用时间">
            </el-table-column>
            <el-table-column prop="nickName" header-align="center" align="center" label="使用用户">
                <template slot-scope="scope">
                    <span>{{ scope.row.userPhone }}</span>
                    <span>{{ scope.row.nickName }}</span>
                </template>
            </el-table-column>
            <!-- <el-table-column prop="codePath" header-align="center" align="center" label="文件地址">
                <template slot-scope="scope">
                    <div class="demo-image__preview">
                        <el-image style="width: 36px; height: 36px" :src="scope.row.codePath"
                            :preview-src-list="[scope.row.codePath]" />
                    </div>
                </template>
            </el-table-column> -->
            <el-table-column prop="url" header-align="center" align="center" label="二维码">
                <template slot-scope="scope">
                    <el-button @click="showQrCode(scope.row)">查看二维码</el-button>
                </template>
            </el-table-column>
            <el-table-column prop="createTime" header-align="center" align="center" label="创建时间">
            </el-table-column>
            <el-table-column prop="updateTime" header-align="center" align="center" label="更新时间">
            </el-table-column>
            <el-table-column fixed="right" header-align="center" align="center" width="150" label="操作">
                <template slot-scope="scope">
                    <el-button type="text" size="small" @click="addOrUpdateHandle(scope.row.id)">修改</el-button>
                    <el-button type="text" size="small" @click="deleteHandle(scope.row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle"
            :current-page="dataForm.page" :page-sizes="[10, 20, 50, 100]" :page-size="dataForm.limit" :total="totalPage"
            layout="total, sizes, prev, pager, next, jumper">
        </el-pagination>

        <!-- 表单弹窗, 新增数据和修改数据 -->
        <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>

        <!-- 批量更新 -->
        <batchUpdate v-if="batchUpdateVisible" ref="batchUpdate" @refreshDataList="getDataList"></batchUpdate>

        <!-- 查看二维码 -->
        <el-dialog title="二维码" :visible.sync="dialogVisible" width="230px">
            <vue-qr :text="item.url" :size="200"></vue-qr>
        </el-dialog>
    </div>
</template>

<script>
import vueQr from "vue-qr";
import axios from 'axios'
import { Notification, MessageBox, Message, Loading } from 'element-ui'
import AddOrUpdate from './integralcode-add-and-update'
import batchUpdate from './batch-update'
import * as api from '@/api/integralCode.js'
import { tansParams, blobValidate } from "@/utils/ruoyi";
import SettingMer from '@/utils/settingMer'
import { isPhone } from "@/libs/wechat";
import { saveAs } from 'file-saver'
export default {
    data() {
        return {
            dataForm: {
                key: '',
                page: 1,
                limit: 10,
            },
            dataList: [],
            pageIndex: 1,
            pageSize: 10,
            totalPage: 0,
            dataListLoading: false,
            dataListSelections: [],
            addOrUpdateVisible: false,
            batchUpdateVisible: false,
            dialogVisible: false,
            item: {},
            ids:[]
        }
    },
    components: {
        AddOrUpdate,
        batchUpdate,
        vueQr
    },
    created() {
        this.getDataList()
    },
    activated() {
        this.getDataList()
    },
    methods: {
        batchUpdate() {
            this.batchUpdateVisible = true
            this.$nextTick(() => {
                this.$refs.batchUpdate.init(this.ids)
            })
        },
        showQrCode(row) {
            this.item = row;
            this.dialogVisible = true
        },
        exportExcel() {
            api.integralcodeExportApi(this.dataForm).then(res => {
                window.open(res.fileName);
            })
        },
        exportData() {
            this.download('admin/integralcode/exportZip', {
                ...this.dataForm
            }, `码图片_${new Date().getTime()}.zip`)
        },
        exportData2() {
            let downloadLoadingInstance = Loading.service({ text: "正在下载数据，请稍候", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)", })

            let params = {
                ...this.dataForm
            }
            let config = {}

            axios.post(SettingMer.apiBaseURL + 'admin/integralcode/exportZip', params, {
                transformRequest: [(params) => { return tansParams(params) }],
                headers: { 'Content-Type': 'application/json; application/octet-stream' },
                responseType: 'blob',
                ...config
            }).then(async (data) => {
                console.log(data);
                const isBlob = blobValidate(data);
                if (isBlob) {
                    const blob = new Blob([data])
                    console.log(blob);
                    saveAs(blob, `码图片_${new Date().getTime()}.zip`)
                } else {
                    const resText = await data.text();
                    const rspObj = JSON.parse(resText);
                    const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
                    Message.error(errMsg);
                }
                downloadLoadingInstance.close();
            }).catch((r) => {
                console.error(r)
                Message.error('下载文件出现错误，请联系管理员！')
                downloadLoadingInstance.close();
            })
        },
        exportData3() {
            let downloadLoadingInstance = Loading.service({ text: "正在下载数据，请稍候", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)", })

            axios({
                method: "post",
                params: {
                    ...this.dataForm
                },
                url: SettingMer.apiBaseURL + "admin/integralcode/exportZip",
                headers: {
                    "content-type": "application/json; application/octet-stream",
                },
                responseType: "blob",
            })
                .then((response) => {
                    console.log(response);
                    let blob = new Blob([response.data], { type: "application/zip" });
                    console.log(blob);
                    let url = window.URL.createObjectURL(blob);
                    const link = document.createElement("a"); // 创建a标签
                    link.href = url;
                    link.download = "码图片"; // 重命名文件
                    link.click();
                    URL.revokeObjectURL(url); // 释放内存
                    downloadLoadingInstance.close();
                })
                .catch((error) => {
                    console.log(error);
                    downloadLoadingInstance.close();
                });

        },
        // 获取数据列表
        getDataList(from) {
            this.dataListLoading = true
            if (from) {
                this.addOrUpdateVisible = false
                this.batchUpdateVisible = false
            }
            api.integralcodeListApi(this.dataForm).then(res => {
                // TODO 获取数据列表
                this.dataList = res.list
                this.totalPage = res.total
                this.dataListLoading = false
            })
        },
        // 每页数
        sizeChangeHandle(val) {
            this.dataForm.limit = val
            this.pageIndex = 1
            this.getDataList()
        },
        // 当前页
        currentChangeHandle(val) {
            this.dataForm.page = val
            this.getDataList()
        },
        // 多选
        selectionChangeHandle(val) {
            this.dataListSelections = val
            this.ids = val.map(item => item.id)
        },
        // 新增 / 修改
        addOrUpdateHandle(id) {
            this.addOrUpdateVisible = true
            this.$nextTick(() => {
                this.$refs.addOrUpdate.init(id)
            })
        },
        // 删除
        deleteHandle(id) {
            var ids = id ? [id] : this.dataListSelections.map(item => {
                return item.id
            })

            this.$confirm(`您确定进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {

                api.integralcodeDeleteApi(ids).then(res => {
                    // TODO 处理删除
                    this.getDataList()
                })
            })
        }
    }
}


</script>
